<!DOCTYPE html>












  


<html class="theme-next muse use-motion" lang="zh-CN">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2"/>
<meta name="theme-color" content="#fff">



  
  
  <link rel="stylesheet" href="/lib/needsharebutton/needsharebutton.css">




  
  
    
      
    
    
      
    
  <script src="//cdn.bootcss.com/pace/1.0.2/pace.min.js"></script>
  <link href="//cdn.bootcss.com/pace/1.0.2/themes/blue/pace-theme-flash.min.css" rel="stylesheet">







<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />





  <script>
  (function(i,s,o,g,r,a,m){i["DaoVoiceObject"]=r;i[r]=i[r]||function(){(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;a.charset="utf-8";m.parentNode.insertBefore(a,m)})(window,document,"script",('https:' == document.location.protocol ? 'https:' : 'http:') + "//widget.daovoice.io/widget/0f81ff2f.js","daovoice")
  daovoice('init', {
      app_id: "b3c7d22e"
    });
  daovoice('update');
  </script>








  <meta name="baidu-site-verification" content="true" />







  
  
    
  
  <link href="//cdn.jsdelivr.net/fancybox/2.1.5/jquery.fancybox.min.css" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  
    
      
    

    
  

  

  

  
    
      
    

    
  

  
    
    
    <link href="https://fonts.cat.net/css?family=Lato:300,300italic,400,400italic,700,700italic|Roboto Slab:300,300italic,400,400italic,700,700italic|Roboto Slab:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






  

<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=6.4.1" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="https://yfzhou.oss-cn-beijing.aliyuncs.com/blog/img/favicon1.ico?v=6.4.1">


  <link rel="icon" type="image/png" sizes="32x32" href="https://yfzhou.oss-cn-beijing.aliyuncs.com/blog/img/favicon1.ico?v=6.4.1">


  <link rel="icon" type="image/png" sizes="16x16" href="https://yfzhou.oss-cn-beijing.aliyuncs.com/blog/img/favicon1.ico?v=6.4.1">


  <link rel="mask-icon" href="https://yfzhou.oss-cn-beijing.aliyuncs.com/blog/img/favicon1.ico?v=6.4.1" color="#fff">









<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Muse',
    version: '6.4.1',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":true,"onmobile":true},
    fancybox: true,
    fastclick: false,
    lazyload: false,
    tabs: true,
    motion: {"enable":true,"async":true,"transition":{"post_block":"perspectiveLeftIn","post_header":"fadeIn","post_body":"fadeIn","coll_header":"perspectiveLeftIn","sidebar":"slideUpIn"}},
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"输入关键字","hits_empty":"没有找到与 ${query} 相关的内容","hits_stats":"${hits}条相关记录，共耗时${time} ms"}
    }
  };
</script>


  



<script>
    (function(){
        if(''){
            if (prompt('请输入文章密码') !== ''){
                alert('密码错误！');
                if (history.length === 1) {
                    location.replace("https://yfzhou.coding.me/"); // 这里替换成你的首页
                } else {
                    history.back();
                }
            }
        }
    })();
</script>

  <meta name="description" content="FreeMarker是一个很值得去学习的模版引擎。它是基于模板文件生成其他文本的通用工具。">
<meta name="keywords" content="java,FreeMarker,模板引擎">
<meta property="og:type" content="article">
<meta property="og:title" content="FreeMarker笔记">
<meta property="og:url" content="https://yfzhou.coding.me/2018/08/01/FreeMarker笔记/index.html">
<meta property="og:site_name" content="Felix">
<meta property="og:description" content="FreeMarker是一个很值得去学习的模版引擎。它是基于模板文件生成其他文本的通用工具。">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="https://note.youdao.com/yws/api/personal/file/7F3E305ECC7C4D43B3723E432DABD9F5?method=download&shareKey=871330817cb4fa023023ff95f9c3a3de">
<meta property="og:image" content="https://note.youdao.com/yws/api/personal/file/65DD084F98E647AB86F1D08C5440559F?method=download&shareKey=78c42c5bd58a114675064cd0e0386924">
<meta property="og:updated_time" content="2019-04-17T08:59:25.009Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="FreeMarker笔记">
<meta name="twitter:description" content="FreeMarker是一个很值得去学习的模版引擎。它是基于模板文件生成其他文本的通用工具。">
<meta name="twitter:image" content="https://note.youdao.com/yws/api/personal/file/7F3E305ECC7C4D43B3723E432DABD9F5?method=download&shareKey=871330817cb4fa023023ff95f9c3a3de">



  <link rel="alternate" href="/atom.xml" title="Felix" type="application/atom+xml" />




  <link rel="canonical" href="https://yfzhou.coding.me/2018/08/01/FreeMarker笔记/"/>



<script type="text/javascript" id="page.configurations">
  CONFIG.page = {
    sidebar: "",
  };
</script>

  <title>FreeMarker笔记 | Felix</title>
  









  <noscript>
  <style type="text/css">
    .use-motion .motion-element,
    .use-motion .brand,
    .use-motion .menu-item,
    .sidebar-inner,
    .use-motion .post-block,
    .use-motion .pagination,
    .use-motion .comments,
    .use-motion .post-header,
    .use-motion .post-body,
    .use-motion .collection-title { opacity: initial; }

    .use-motion .logo,
    .use-motion .site-title,
    .use-motion .site-subtitle {
      opacity: initial;
      top: initial;
    }

    .use-motion {
      .logo-line-before i { left: initial; }
      .logo-line-after i { right: initial; }
    }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Felix</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
    
      
        <p class="site-subtitle">Viva La Vida</p>
      
    
  </div>

  <div class="site-nav-toggle">
    <button aria-label="切换导航栏">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>



<nav class="site-nav">
  
    <ul id="menu" class="menu">
      
        
        
        
          
          <li class="menu-item menu-item-home">
    <a href="/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-home"></i> <br />首页</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-tags">
    <a href="/tags/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />标签</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-categories">
    <a href="/categories/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-th"></i> <br />分类</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-archives">
    <a href="/archives/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />归档</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-top">
    <a href="/top/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-signal"></i> <br />TopX</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-sitemap">
    <a href="/sitemap.xml" rel="section">
      <i class="menu-item-icon fa fa-fw fa-sitemap"></i> <br />站点地图</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-about">
    <a href="/about/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-user"></i> <br />关于</a>
  </li>

      
      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />搜索</a>
        </li>
      
    </ul>
  

  
    

  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="输入关键字搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



  



</div>
    </header>

    


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://yfzhou.coding.me/2018/08/01/FreeMarker笔记/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Felix">
      <meta itemprop="description" content="周宇峰的博客">
      <meta itemprop="image" content="https://yfzhou.oss-cn-beijing.aliyuncs.com/blog/img/user_head_img.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Felix">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">FreeMarker笔记
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">

            
            
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              

              
                
              

              <time title="创建时间：2018-08-01 09:24:56" itemprop="dateCreated datePublished" datetime="2018-08-01T09:24:56+08:00">2018-08-01</time>
            

            
              

              
                
                <span class="post-meta-divider">|</span>
                

                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                
                  <span class="post-meta-item-text">更新于</span>
                
                <time title="修改时间：2019-04-17 16:59:25" itemprop="dateModified" datetime="2019-04-17T16:59:25+08:00">2019-04-17</time>
              
            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/categories/java/" itemprop="url" rel="index"><span itemprop="name">java</span></a></span>

                
                
              
            </span>
          

          
            
          

          
          
             <span id="/2018/08/01/FreeMarker笔记/" class="leancloud_visitors" data-flag-title="FreeMarker笔记">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数：</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          
            <div class="post-symbolscount">
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-edit"></i>
                </span>
                
                  <span class="post-meta-item-text">本文字数：</span>
                
                <span title="本文字数">15k</span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">19 分钟</span>
              
            </div>
          

          
              <div class="post-description">FreeMarker是一个很值得去学习的模版引擎。它是基于模板文件生成其他文本的通用工具。</div>
          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p><span><br><a id="more"></a></span></p>
<h5 id="FreeMarker是一个很值得去学习的模版引擎。它是基于模板文件生成其他文本的通用工具。本章内容通过如何使用FreeMarker生成Html-web-页面-和-代码自动生成工具来快速了解FreeMarker。"><a href="#FreeMarker是一个很值得去学习的模版引擎。它是基于模板文件生成其他文本的通用工具。本章内容通过如何使用FreeMarker生成Html-web-页面-和-代码自动生成工具来快速了解FreeMarker。" class="headerlink" title="FreeMarker是一个很值得去学习的模版引擎。它是基于模板文件生成其他文本的通用工具。本章内容通过如何使用FreeMarker生成Html web 页面 和 代码自动生成工具来快速了解FreeMarker。"></a>FreeMarker是一个很值得去学习的模版引擎。它是基于模板文件生成其他文本的通用工具。本章内容通过如何使用FreeMarker生成Html web 页面 和 代码自动生成工具来快速了解FreeMarker。</h5><h3 id="简介"><a href="#简介" class="headerlink" title="简介"></a>简介</h3><p>FreeMarker是一款用java语言编写的模版引擎，它虽然不是web应用框架，但它很合适作为web应用框架的一个组件。</p>
<h5 id="特点"><a href="#特点" class="headerlink" title="特点"></a>特点</h5><ol>
<li>==轻量级==模版引擎，不需要Servlet环境就可以很轻松的嵌入到应用程序中</li>
<li>能生成各种文本，如html，xml，java，等</li>
<li>入门==简单==，它是用java编写的，很多语法和java相似</li>
</ol>
<h3 id="FreeMarker-程序"><a href="#FreeMarker-程序" class="headerlink" title="FreeMarker 程序"></a>FreeMarker 程序</h3><p>这里通过模拟简单的代码自动生产工具来感受第一个FreeMarker程序。</p>
<h6 id="项目目录结构"><a href="#项目目录结构" class="headerlink" title="项目目录结构"></a>项目目录结构</h6><p><img src="https://note.youdao.com/yws/api/personal/file/7F3E305ECC7C4D43B3723E432DABD9F5?method=download&amp;shareKey=871330817cb4fa023023ff95f9c3a3de" alt="image"></p>
<h6 id="eclipse安装freemarker插件"><a href="#eclipse安装freemarker插件" class="headerlink" title="eclipse安装freemarker插件"></a>eclipse安装freemarker插件</h6><div class="note default no-icon"><p>Help –&gt; Install New Software<br>点add，再出来的对话框中的Location中输入：<a href="http://download.jboss.org/jbosstools/updates/stable/indigo/" target="_blank" rel="noopener">http://download.jboss.org/jbosstools/updates/stable/indigo/</a><br>name随便取一个即可。然后会列出来所有可用的插件，<br>JBoss Application Development 下找到 FreeMarker IDE选中 点击Next<br>安装好重启eclipse就可以了。<br>过程可能有点慢，请==耐心等待==。</p></div>

<h6 id="maven依赖"><a href="#maven依赖" class="headerlink" title="maven依赖"></a>maven依赖</h6><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">&lt;dependency&gt;</span><br><span class="line">	&lt;groupId&gt;org.freemarker&lt;/groupId&gt;</span><br><span class="line">	&lt;artifactId&gt;freemarker&lt;/artifactId&gt;</span><br><span class="line">	&lt;version&gt;2.3.23&lt;/version&gt;</span><br><span class="line">&lt;/dependency&gt;</span><br></pre></td></tr></table></figure>
<p>hello.ftl模板(部分)<br><img src="https://note.youdao.com/yws/api/personal/file/65DD084F98E647AB86F1D08C5440559F?method=download&amp;shareKey=78c42c5bd58a114675064cd0e0386924" alt="image"></p>
<p>FreeMarkerDemo.java 核心方法，使用 FreeMarker 模版引擎。<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br></pre></td><td class="code"><pre><span class="line">package com.freemarker.hello.templates;</span><br><span class="line"></span><br><span class="line">import java.io.BufferedWriter;</span><br><span class="line">import java.io.File;</span><br><span class="line">import java.io.FileOutputStream;</span><br><span class="line">import java.io.OutputStreamWriter;</span><br><span class="line">import java.io.Writer;</span><br><span class="line">import java.util.ArrayList;</span><br><span class="line">import java.util.Date;</span><br><span class="line">import java.util.HashMap;</span><br><span class="line">import java.util.List;</span><br><span class="line">import java.util.Map;</span><br><span class="line"></span><br><span class="line">import com.freemarker.hello.pojo.User;</span><br><span class="line"></span><br><span class="line">import freemarker.template.Configuration;</span><br><span class="line">import freemarker.template.Template;</span><br><span class="line"></span><br><span class="line">/**</span><br><span class="line"> * 最常见的问题： java.io.FileNotFoundException: xxx does not exist. 解决方法：要有耐心</span><br><span class="line"> * FreeMarker jar 最新的版本（2.3.23）提示 Configuration 方法被弃用 代码自动生产基本原理： 数据填充</span><br><span class="line"> * freeMarker 占位符</span><br><span class="line"> */</span><br><span class="line">public class FreeMarkerDemo &#123;</span><br><span class="line"></span><br><span class="line">	private static final String TEMPLATE_PATH = &quot;src/main/java/com/freemarker/hello/templates&quot;;</span><br><span class="line">	private static final String CLASS_PATH = &quot;src/main/java/com/freemarker/hello&quot;;</span><br><span class="line">	private static List&lt;User&gt; users = new ArrayList&lt;User&gt;();</span><br><span class="line"></span><br><span class="line">	static &#123;</span><br><span class="line">		User u1 = new User(&quot;1&quot;, 22, &quot;迟到峰&quot;);</span><br><span class="line">		User u2 = new User(&quot;2&quot;, 23, &quot;要饭楚&quot;);</span><br><span class="line">		User u3 = new User(&quot;3&quot;, 27, &quot;BUG李&quot;);</span><br><span class="line">		User u4 = new User(&quot;4&quot;, 25, &quot;删库冬&quot;);</span><br><span class="line">		User u5 = new User(&quot;5&quot;, 29, &quot;瓜子军&quot;);</span><br><span class="line">		User u6 = new User(&quot;6&quot;, 28, &quot;老韩&quot;);</span><br><span class="line">		User u7 = new User(null, 25, null);</span><br><span class="line">		users.add(u1);</span><br><span class="line">		users.add(u2);</span><br><span class="line">		users.add(u3);</span><br><span class="line">		users.add(u4);</span><br><span class="line">		users.add(u5);</span><br><span class="line">//		users.add(null);</span><br><span class="line">		users.add(u6);</span><br><span class="line">//		users.add(u7);</span><br><span class="line">//		users.clear();</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	public static void main(String[] args) &#123;</span><br><span class="line">		// step1 创建freeMarker配置实例</span><br><span class="line">		Configuration configuration = new Configuration(Configuration.VERSION_2_3_23);</span><br><span class="line">		Writer out = null;</span><br><span class="line">		try &#123;</span><br><span class="line">			// step2 获取模版路径</span><br><span class="line">			configuration.setDirectoryForTemplateLoading(new File(TEMPLATE_PATH));</span><br><span class="line">			// step3 创建数据模型</span><br><span class="line">			Map&lt;String, Object&gt; dataMap = new HashMap&lt;String, Object&gt;();</span><br><span class="line">			dataMap.put(&quot;classPath&quot;, &quot;com.freemarker.hello&quot;);</span><br><span class="line">			dataMap.put(&quot;htmlName&quot;, &quot;使用FreeMarker生成html模板&quot;);</span><br><span class="line">			dataMap.put(&quot;helloWorld&quot;, &quot;通过简单的 &lt;代码自动生产程序&gt; 演示 FreeMarker的HelloWorld！&quot;);</span><br><span class="line">			dataMap.put(&quot;author&quot;, &quot;周宇峰&quot;);</span><br><span class="line">			dataMap.put(&quot;github&quot;, &quot;github.com/542869246&quot;);</span><br><span class="line">			dataMap.put(&quot;name&quot;, &quot;abcdefg&quot;);</span><br><span class="line">			dataMap.put(&quot;dateTime&quot;,new Date());</span><br><span class="line">			dataMap.put(&quot;users&quot;, users);</span><br><span class="line">			</span><br><span class="line">			// step4 加载模版文件</span><br><span class="line">			Template template = configuration.getTemplate(&quot;hello.ftl&quot;);</span><br><span class="line">			// step5 生成数据</span><br><span class="line">			File docFile = new File(CLASS_PATH + &quot;\\&quot; + &quot;hello.html&quot;);</span><br><span class="line">			out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(docFile)));</span><br><span class="line">			// step6 输出文件</span><br><span class="line">			template.process(dataMap, out);</span><br><span class="line">			System.out.println(&quot;文件创建成功 !&quot;);</span><br><span class="line">		&#125; catch (Exception e) &#123;</span><br><span class="line">			e.printStackTrace();</span><br><span class="line">		&#125; finally &#123;</span><br><span class="line">			try &#123;</span><br><span class="line">				if (null != out) &#123;</span><br><span class="line">					out.flush();</span><br><span class="line">				&#125;</span><br><span class="line">			&#125; catch (Exception e2) &#123;</span><br><span class="line">				e2.printStackTrace();</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>运行程序后刷新项目，会发现多了一个hello.html文件。</p>
<h2 id="语法详解"><a href="#语法详解" class="headerlink" title="语法详解"></a>语法详解</h2><h3 id="数据类型"><a href="#数据类型" class="headerlink" title="数据类型"></a>数据类型</h3><h6 id="和java不同，FreeMarker不需要定义变量的类型，直接赋值即可。"><a href="#和java不同，FreeMarker不需要定义变量的类型，直接赋值即可。" class="headerlink" title="和java不同，FreeMarker不需要定义变量的类型，直接赋值即可。"></a>和java不同，FreeMarker不需要定义变量的类型，直接赋值即可。</h6><p>字符串： value = “xxxx” 。 单引号和双引号是一样的。字符串中可以使用转义字符”\”。如果字符串内有大量的特殊字符，则可以在引号的前面加上一个字母r，则字符串内的所有字符都将直接输出。string = r”xxxx”。</p>
<p>数值：value = 1.2。数值可以直接等于，但是不能用科学计数法。</p>
<p>布尔值：true or false。</p>
<p>List集合：list = [1,2,3] ; list=[1..100] 表示 1 到 100 的集合，反之亦然。</p>
<p>Map集合：map = {“key” : “value” , “key2” : “value2”}，key 必须是字符串</p>
<p>时间对象:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">root.put(&quot;date1&quot;,new Date());</span><br><span class="line">$&#123;date1?string(&quot;yyyy-MM-dd HH:mm:ss&quot;)&#125;</span><br></pre></td></tr></table></figure>
<p>JaveBean：Freemarker中对于javabean的处理跟EL表达式一致，类型可自动转化！非常方便！</p>
<h6 id="注释：-lt-–-abcd-–-gt"><a href="#注释：-lt-–-abcd-–-gt" class="headerlink" title="注释：&lt;#– abcd –&gt;"></a>注释：&lt;#– abcd –&gt;</h6><h3 id="字符串操作"><a href="#字符串操作" class="headerlink" title="字符串操作"></a>字符串操作</h3><h6 id="声明变量和输出"><a href="#声明变量和输出" class="headerlink" title="声明变量和输出:"></a>声明变量和输出:</h6><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">&lt;#assign name=&quot;zyf&quot;&gt;         //声明一个变量值为zyf的变量name</span><br><span class="line">$&#123;name&#125;                      //输出name  结果为zyf</span><br><span class="line">&lt;#assign cname=r&quot;特殊字符完成输出(https://github.com/542869246)&quot;&gt;</span><br><span class="line">$&#123;cname&#125;</span><br></pre></td></tr></table></figure>
<h5 id="字符串连接："><a href="#字符串连接：" class="headerlink" title="字符串连接："></a>字符串连接：</h5><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">//使用嵌套或者+ 进行字符串连接操作</span><br><span class="line">$&#123;&quot;Hello $&#123;name&#125; !&quot;&#125; / $&#123;&quot;Hello &quot; + name + &quot; !&quot;&#125;</span><br><span class="line">//输出：Hello zyf ! / Hello zyf !</span><br></pre></td></tr></table></figure>
<h5 id="字符串截取："><a href="#字符串截取：" class="headerlink" title="字符串截取："></a>字符串截取：</h5><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">&lt;#assign a=&quot;abcdefg&quot;&gt;</span><br><span class="line">$&#123;a[1]&#125;                     //b</span><br><span class="line">$&#123;a[1..5]&#125;                  //bcdef</span><br><span class="line">$&#123;a?substring(3)&#125;           //efg</span><br><span class="line">$&#123;a?substring(3,2)&#125;         //ef</span><br></pre></td></tr></table></figure>
<div class="note default"><p>string[index]。index 可以是一个值，也可以是形如 0..2 表示下标从0开始，到下标为2结束。一共是三个数。<br>substring（start,end）从一个字符串中截取子串。<br>start:截取子串开始的索引，start必须大于等于0，小于等于end。<br>end: 截取子串的长度，end必须大于等于0，小于等于字符串长度，如果省略该参数，默认为字符串长度。</p></div>

<h3 id="算数运算："><a href="#算数运算：" class="headerlink" title="算数运算："></a>算数运算：</h3><p>支持”+”、”－”、”*”、”/“、”%”运算符</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">&lt;#assign number1=10 number2=5 &gt;</span><br><span class="line">&quot;+&quot;:$&#123;number1 + number2 &#125;       //15</span><br><span class="line">&quot;-&quot;:$&#123;number1 - number2 &#125;       //5</span><br><span class="line">&quot;*&quot;:$&#123;number1 * number2 &#125;       //50</span><br><span class="line">&quot;/&quot;:$&#123;number1 / number2 &#125;       //2</span><br><span class="line">&quot;%&quot;:$&#123;number1 % number2 &#125;       //0</span><br></pre></td></tr></table></figure>
<h3 id="比较运算符"><a href="#比较运算符" class="headerlink" title="比较运算符"></a>比较运算符</h3><p>表达式中支持的比较运算符有如下几种：</p>
<ol>
<li>=（或者==）：判断两个值是否相等；</li>
<li>!=：判断两个值是否不相等；<br>注： =和!=可以用作字符串、数值和日期的比较，但两边的数据类型必须相同。而且FreeMarker的比较是精确比较，==不会忽略大小写及空格==。</li>
<li>>（或者gt）：大于</li>
<li>>=（或者gte）：大于等于</li>
<li>&lt;（或者lt）：小于</li>
<li>&lt;=（或者lte）：小于等于</li>
<li><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">&lt;#if number1 + number2 gte 12 || number1 - number2 lt 6&gt;</span><br><span class="line">&quot;*&quot; : $&#123;number1 * number2&#125;</span><br><span class="line">&lt;#else&gt;</span><br><span class="line">&quot;/&quot; : $&#123;number1 / number2&#125;</span><br><span class="line">&lt;/#if&gt;</span><br></pre></td></tr></table></figure>
</li>
</ol>
<div class="note info"><p>上面这些比较运算符可以用于数字和日期，但不能用于字符串。大部分时候，使用==gt比&gt;有更好的效果==，因为FreeMarker会把&gt;解释成标签的结束字符。可以使用括号来避免这种情况，如：&lt;#if (x&gt;y)&gt;。</p></div>

<h3 id="逻辑运算符"><a href="#逻辑运算符" class="headerlink" title="逻辑运算符"></a>逻辑运算符</h3><ol>
<li>&amp;&amp;：逻辑与；</li>
<li>||：逻辑或；</li>
<li>!：逻辑非<div class="note info"><p>逻辑运算符只能用于布尔值。</p></div>

</li>
</ol>
<h3 id="内建函数"><a href="#内建函数" class="headerlink" title="内建函数"></a>内建函数</h3><div class="note info"><p>FreeMarker还提供了一些内建函数来转换输出,可以在任何变量后紧跟?,?后紧跟内建函数,就可以通过内建函数来轮换输出变量.下面是常用的内建的字符串函数</p></div>

<h5 id="字符串相关常用的内建函数："><a href="#字符串相关常用的内建函数：" class="headerlink" title="字符串相关常用的内建函数："></a>字符串相关常用的内建函数：</h5><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line">&lt;#assign data = &quot;abcd1234&quot;&gt;</span><br><span class="line">html：对字符串进行HTML编码，将字符串中的&lt;、&gt;、&amp;和“替换为对应得&amp;lt;&amp;gt;&amp;quot:&amp;amp</span><br><span class="line"></span><br><span class="line">cap_first：使字符串第一个字母大写 $&#123;data?cap_first&#125;</span><br><span class="line"></span><br><span class="line">lower_case：将字符串转成小写 $&#123;data?lower_case&#125;</span><br><span class="line"></span><br><span class="line">upper_case：将字符串转成大写 $&#123;data?upper_case&#125;</span><br><span class="line"></span><br><span class="line">trim:去掉字符串前后的空白字符 $&#123;data?trim&#125;</span><br><span class="line"></span><br><span class="line">length:返回字符串的长度 $&#123;&quot;string&quot;?length&#125;</span><br><span class="line"></span><br><span class="line">index_of(substring,start)在字符串中查找某个子串，返回找到子串的第一个字符的索引，如果没有找到子串，则返回-1。</span><br><span class="line">Start参数用于指定从字符串的那个索引处开始搜索，start为数字值。</span><br><span class="line">如果start大于字符串长度，则start取值等于字符串长度，如果start小于0， 则start取值为0。</span><br><span class="line">$&#123;&quot;string&quot;?index_of(&quot;in&quot;) 结果为3</span><br><span class="line">$&#123;&quot;string&quot;?index_of(&quot;ab&quot;) 结果为-1</span><br><span class="line"></span><br><span class="line">replace用于将字符串中的一部分从左到右替换为另外的字符串。</span><br><span class="line">$&#123;&quot;strabg&quot;?replace(&quot;ab&quot;,&quot;in&quot;)&#125; 结果为string</span><br><span class="line"></span><br><span class="line">split使用指定的分隔符将一个字符串拆分为一组字符串</span><br><span class="line">&lt;#list &quot;This|is|split&quot;?split(&quot;|&quot;&quot;) as s&gt;</span><br><span class="line">$&#123;s&#125;</span><br><span class="line">&lt;/#list&gt;</span><br><span class="line">结果为:</span><br><span class="line">This</span><br><span class="line">is</span><br><span class="line">split</span><br></pre></td></tr></table></figure>
<h5 id="集合相关常用的内建函数："><a href="#集合相关常用的内建函数：" class="headerlink" title="集合相关常用的内建函数："></a>集合相关常用的内建函数：</h5><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">size：获得集合中元素的个数 $&#123;users?size&#125;</span><br></pre></td></tr></table></figure>
<h5 id="数字值相关常用的内建函数："><a href="#数字值相关常用的内建函数：" class="headerlink" title="数字值相关常用的内建函数："></a>数字值相关常用的内建函数：</h5><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">&lt;#assign floatData = 12.34&gt;</span><br><span class="line">int：取得数字的整数部分 $&#123;floatData?int&#125;</span><br></pre></td></tr></table></figure>
<h3 id="三元运算符"><a href="#三元运算符" class="headerlink" title="三元运算符"></a>三元运算符</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">$&#123;(users?size gt 15)?string(&apos;a&apos;,&apos;b&apos;) &#125;</span><br><span class="line">&lt;#assign theValue = (temp == &quot;default&quot;)?string(&apos;true&apos;,&apos;false&apos;) /&gt;</span><br></pre></td></tr></table></figure>
<h3 id="空值处理运算符"><a href="#空值处理运算符" class="headerlink" title="空值处理运算符"></a>空值处理运算符</h3><div class="note default no-icon"><p>FreeMarker对空值的处理非常严格,==FreeMarker的变量必须有值==,没有被赋值的变量就会抛出异常,因为FreeMarker未赋值的变量强制出错可以杜绝很多潜在的错误,如缺失潜在的变量命名,或者其他变量错误.这里所说的空值,实际上也包括那些并不存在的变量,对于一个Java的 null值而言,我们认为这个变量是存在的,只是它的值为null,但对于FreeMarker模板而言,它无法理解null值,null值和不存在的变量完全相同。</p></div>

<h6 id="FreeMarker提供两个运算符来避免空值"><a href="#FreeMarker提供两个运算符来避免空值" class="headerlink" title="FreeMarker提供两个运算符来避免空值"></a>FreeMarker提供两个运算符来避免空值</h6><ol>
<li>!：指定缺失变量的默认值</li>
<li>??：判断变量是否存在</li>
</ol>
<div class="note default no-icon"><p>!运算符有两种用法：variable!或variable!defaultValue。第一种用法不给变量指定默认值，表明默认值是空字符串、长度为0的集合、或长度为0的Map对象。==使用!运算符指定默认值并不要求默认值的类型和变量类型相同==。</p></div>

<div class="note default no-icon"><p>??运算符返回布尔值，如：variable??，如果变量存在，返回true，否则返回false。</p></div>

<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">&lt;#if user??&gt;</span><br><span class="line">    $&#123;user.name!&quot;变量为空则给一个默认值&quot;&#125;</span><br><span class="line">&lt;#else&gt;</span><br><span class="line">    users为空</span><br><span class="line">&lt;/#if&gt;</span><br></pre></td></tr></table></figure>
<h3 id="常用指令"><a href="#常用指令" class="headerlink" title="常用指令"></a>常用指令</h3><div class="note default no-icon"><p>FreeMarker的FTL指令也是模板的重要组成部分,这些指令可实现对数据模型所包含数据的抚今迭代,分支控制.除此之外,还有一些重要的功能,也是通过FTL指令来实现的. </p></div>


<h4 id="if指令"><a href="#if指令" class="headerlink" title="if指令"></a>if指令</h4><p>这是一个典型的分支控制指令,该指令的作用完全类似于Java语言中的if,if指令的语法格式如下<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">&lt;#assign age=23&gt; </span><br><span class="line">&lt;#if (age&gt;60)&gt;老年人 </span><br><span class="line">&lt;#elseif (age&gt;40)&gt;中年人 </span><br><span class="line">&lt;#elseif (age&gt;20)&gt;青年人 </span><br><span class="line">&lt;#else&gt; 少年人 </span><br><span class="line">&lt;/#if&gt;</span><br></pre></td></tr></table></figure></p>
<h4 id="switch-case指令"><a href="#switch-case指令" class="headerlink" title="switch case指令"></a>switch case指令</h4><p>switch（expr）,其中expr只能是字符串、基本类型int或者包装类Integer，也包括不同的长度整型，例如short<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">&lt;#switch being.size&gt;  </span><br><span class="line">  &lt;#case &quot;small&quot;&gt;  </span><br><span class="line">          This will be processed if it is small  </span><br><span class="line">          &lt;#break&gt;  </span><br><span class="line">  &lt;#case &quot;medium&quot;&gt;  </span><br><span class="line">          This will be processed if it is medium  </span><br><span class="line">          &lt;#break&gt;  </span><br><span class="line">  &lt;#case &quot;large&quot;&gt;  </span><br><span class="line">          This will be processed if it is large  </span><br><span class="line">          &lt;#break&gt;  </span><br><span class="line">  &lt;#default&gt;  </span><br><span class="line">          This will be processed if it is neither  </span><br><span class="line">&lt;/#switch&gt;</span><br></pre></td></tr></table></figure></p>
<h4 id="list指令"><a href="#list指令" class="headerlink" title="list指令"></a>list指令</h4><div class="note default no-icon"><p>list指令是一个迭代输出指令,用于迭代输出数据模型中的集合<br>sequence是集合(collection)的表达式，item是循环变量的名字，不能是表达式。<br>当在遍历sequence时，会将遍历变量的值保存到item中</p></div>

<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">//格式</span><br><span class="line">&lt;#list sequence as item&gt;    </span><br><span class="line">  $&#123;item&#125;   </span><br><span class="line">&lt;/#list&gt;</span><br><span class="line"></span><br><span class="line">//遍历users集合 获取user对象属性</span><br><span class="line">&lt;#list users as user&gt;    </span><br><span class="line">  $&#123;user.id&#125;--$&#123;user.age&#125;--&#123;user.name&#125;</span><br><span class="line">&lt;/#list&gt;</span><br></pre></td></tr></table></figure>
<h6 id="List指令还隐含了两个循环变量："><a href="#List指令还隐含了两个循环变量：" class="headerlink" title="List指令还隐含了两个循环变量："></a>List指令还隐含了两个循环变量：</h6><p>item_index:当前迭代项在所有迭代项中的位置，是数字值。</p>
<p>item_has_next:用于判断当前迭代项是否是所有迭代项中的最后一项。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">&lt;#list users as user&gt;    </span><br><span class="line">  $&#123;user_index&#125;--$&#123;user.id&#125;--$&#123;user.age&#125;--&#123;user.name&#125;</span><br><span class="line">    &lt;#if !user_has_next&gt;</span><br><span class="line">        共有$&#123;users?size&#125;最后一个用户是:$&#123;user.name&#125;</span><br><span class="line">    &lt;/#if&gt;</span><br><span class="line">&lt;/#list&gt;</span><br></pre></td></tr></table></figure>
<h6 id="对List进行排序"><a href="#对List进行排序" class="headerlink" title="对List进行排序"></a>对List进行排序</h6><div class="note default no-icon"><p>通常我们的排序操作都是通过DAO层来实现的，如果我们想随时更改我们的排序，那么就必须修改我们的DAO层代码，确实不方便。但Freemarker为我们提供了这样的排序方法，解决了这个问题。</p></div>

<ol>
<li>sort升序排序函数<br>sort对序列(sequence)进行排序，要求序列中的变量必须是：字符串（按首字母排序）,数字，日期值。</li>
</ol>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&lt;#list list?sort as l&gt;…&lt;/#list&gt;</span><br></pre></td></tr></table></figure>
<ol start="2">
<li>sort_by函数<br>sort_by有一个参数,该参数用于指定想要排序的子变量，排序是按照变量对应的值进行排序,如：</li>
</ol>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&lt;#list users?sort_by(&quot;age&quot;) as user&gt;…&lt;/#list&gt;</span><br></pre></td></tr></table></figure>
<p>age是User对象的属性，排序是按age的值进行的。</p>
<ol start="3">
<li>reverse降序排序函数</li>
</ol>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&lt;#list list? reverse as l&gt;…&lt;/#list&gt;。</span><br></pre></td></tr></table></figure>
<p>reverse使用同sort相同。reverse还可以同sort_by一起使用<br>如：想让用户按年龄降序排序，那么可以这个样写</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&lt;#list users?sort_by(&quot;age&quot;)?reverse as user&gt;…&lt;/#list&gt;</span><br></pre></td></tr></table></figure>
<h5 id="使用list指令遍历map"><a href="#使用list指令遍历map" class="headerlink" title="使用list指令遍历map"></a>使用list指令遍历map</h5><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line">//创建一个map,注意在freemarker中,map的key只能是字符串来作为key</span><br><span class="line">&lt;#assign userMap=&#123;&quot;1&quot;,&quot;刘德华&quot;,&quot;2&quot;:&quot;张学友&quot;&#125;/&gt;</span><br><span class="line"></span><br><span class="line">//获取map中的值</span><br><span class="line">$&#123;userMap[&quot;1&quot;]&#125;</span><br><span class="line"></span><br><span class="line">//获取map的keys</span><br><span class="line">&lt;#assign  keys=userMap?keys/&gt;</span><br><span class="line"></span><br><span class="line">//遍历map 首选获取key的集合</span><br><span class="line">&lt;#list keys as key&gt;</span><br><span class="line">  key:$&#123;key&#125;-value:$&#123;userMap[&quot;$&#123;key&#125;&quot;]&#125;</span><br><span class="line">&lt;/#list&gt;</span><br><span class="line"></span><br><span class="line">//直接遍历map的第二种方式</span><br><span class="line">&lt;#list userMap?keys as key&gt;</span><br><span class="line">  key:$&#123;key&#125;--value:$&#123;userMap[&quot;$&#123;key&#125;&quot;]&#125;</span><br><span class="line">&lt;/#list&gt;</span><br><span class="line"></span><br><span class="line">//直接遍历map的values</span><br><span class="line">&lt;#list userMap?values as value&gt;</span><br><span class="line"> $&#123;value&#125;</span><br><span class="line">&lt;/#list&gt;</span><br></pre></td></tr></table></figure>
<h4 id="include指令"><a href="#include指令" class="headerlink" title="include指令"></a>include指令</h4><p>include指令的作用类似于JSP的包含指令,用于包含指定页</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">现在有hello.ftl、inc1.ftl与inc2.ftl 3个模板</span><br><span class="line">在inc1.ftl与inc2.ftl中的内容分别是:</span><br><span class="line">&lt;#assign username=&quot;刘德华&quot;&gt;与&lt;#assign username=&quot;张学友&quot;&gt;</span><br><span class="line"></span><br><span class="line">接着在hello.ftl模版中用include将inc1.ftl包含进来</span><br><span class="line">&lt;#include &quot;/inc/inc1.ftl&quot;&gt;</span><br><span class="line">$&#123;username&#125;</span><br><span class="line">此刻获取的结果是:刘德华</span><br><span class="line"></span><br><span class="line">接着我们在hello.ftl用include将inc1.ftl与inc2.ftl同时进行包含进来</span><br><span class="line"></span><br><span class="line">&lt;#include &quot;/inc/inc1.ftl&quot;&gt;</span><br><span class="line">&lt;#include &quot;/inc/inc2.ftl&quot;&gt;</span><br><span class="line">$&#123;username&#125;</span><br><span class="line"></span><br><span class="line">此刻获取的值是:张学友</span><br></pre></td></tr></table></figure>
<h6 id="总结：出现这种情况，在-两个模版中都分别存在变量名都相同的变量的时候，include包含进来，会进行覆盖-，include只时候将其公共的静态文件进行包含，而里面不涉及到内部函数以及变量声明之类的，当涉及到这种问题，我们就要用import进行导入"><a href="#总结：出现这种情况，在-两个模版中都分别存在变量名都相同的变量的时候，include包含进来，会进行覆盖-，include只时候将其公共的静态文件进行包含，而里面不涉及到内部函数以及变量声明之类的，当涉及到这种问题，我们就要用import进行导入" class="headerlink" title="总结：出现这种情况，在==两个模版中都分别存在变量名都相同的变量的时候，include包含进来，会进行覆盖==，include只时候将其公共的静态文件进行包含，而里面不涉及到内部函数以及变量声明之类的，当涉及到这种问题，我们就要用import进行导入"></a>总结：出现这种情况，在==两个模版中都分别存在变量名都相同的变量的时候，include包含进来，会进行覆盖==，include只时候将其公共的静态文件进行包含，而里面不涉及到内部函数以及变量声明之类的，当涉及到这种问题，我们就要用import进行导入</h6><h4 id="import指令"><a href="#import指令" class="headerlink" title="import指令"></a>import指令</h4><p>该指令用于导入FreeMarker模板中的所有变量,并将该变量放置在指定的Map对象中</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">接着上面</span><br><span class="line">在hello.ftl用import指令将inc1.ftl与inc2.ftll模板文件中的所有变量,同时导入进来</span><br><span class="line">&lt;#import &quot;/inc/inc1.ftl&quot; as inc1&gt;</span><br><span class="line">&lt;#import &quot;/inc/inc2.ftl&quot; as inc2&gt;</span><br><span class="line"></span><br><span class="line">$&#123;inc1.username&#125;    //刘德华</span><br><span class="line">$&#123;inc2.username&#125;    //张学友</span><br></pre></td></tr></table></figure>
<h4 id="noparse指令"><a href="#noparse指令" class="headerlink" title="noparse指令"></a>noparse指令</h4><p>noparse指令指定FreeMarker不处理该指定里包含的内容,该指令的语法格式如下</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">&lt;#noparse&gt;...&lt;/#noparse&gt;</span><br><span class="line"></span><br><span class="line">看如下的例子: </span><br><span class="line">&lt;#noparse&gt; </span><br><span class="line">&lt;#list books as book&gt; </span><br><span class="line">   &lt;tr&gt;&lt;td&gt;$&#123;book.name&#125;&lt;td&gt;作者:$&#123;book.author&#125; </span><br><span class="line">&lt;/#list&gt; </span><br><span class="line">&lt;/#noparse&gt; </span><br><span class="line">输出如下: </span><br><span class="line">&lt;#list books as book&gt; </span><br><span class="line">   &lt;tr&gt;&lt;td&gt;$&#123;book.name&#125;&lt;td&gt;作者:$&#123;book.author&#125; </span><br><span class="line">&lt;/#list&gt;</span><br></pre></td></tr></table></figure>
<h4 id="assign指令"><a href="#assign指令" class="headerlink" title="assign指令"></a>assign指令</h4><div class="note default no-icon"><p>assign指令在前面已经使用了多次,它用于为该模板页面创建或替换一个顶层变量,assign指令的用法有多种,包含创建或替换一个顶层变量, 或者创建或替换多个变量等,它的最简单的语法如下:&lt;#assign name=value [in namespacehash]&gt;,这个用法用于指定一个名为name的变量,该变量的值为value,此外,FreeMarker允许在使用 assign指令里增加in子句,in子句用于将创建的name变量放入namespacehash命名空间中<br>assign指令还有如下用法:</p></div>

<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">&lt;#assign name1=value1 name2=value2 ... nameN=valueN [in namespacehash]&gt;</span><br><span class="line">这个语法可以同时创建或替换多个顶层变量,此外,还有一种复杂的用法,如果需要创建或替换的变量值是一个复杂的表达式,则可以使用如下语法格式:</span><br><span class="line">&lt;#assign name [in namespacehash]&gt;capture this&lt;/#assign&gt;</span><br><span class="line">在这个语法中,是指将assign指令的内容赋值给name变量.如下例子:</span><br><span class="line">&lt;#assign x&gt; </span><br><span class="line">&lt;#list [&quot;星期一&quot;, &quot;星期二&quot;, &quot;星期三&quot;, &quot;星期四&quot;, &quot;星期五&quot;, &quot;星期六&quot;, &quot;星期天&quot;] as n&gt; </span><br><span class="line">$&#123;n&#125; </span><br><span class="line">&lt;/#list&gt; </span><br><span class="line">&lt;/#assign&gt; </span><br><span class="line">$&#123;x&#125; </span><br><span class="line">上面的代码将产生如下输出:星期一 星期二 星期三 星期四 星期五 星期六 星期天</span><br></pre></td></tr></table></figure>
<h6 id="虽然assign指定了这种复杂变量值的用法-但是我们也不要滥用这种用法-如下例子"><a href="#虽然assign指定了这种复杂变量值的用法-但是我们也不要滥用这种用法-如下例子" class="headerlink" title="虽然assign指定了这种复杂变量值的用法,但是我们也不要滥用这种用法,如下例子:"></a>虽然assign指定了这种复杂变量值的用法,但是我们也不要滥用这种用法,如下例子:</h6><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">&lt;#assign x&gt;Hello $&#123;user&#125;!&lt;/#assign&gt;</span><br><span class="line">以上代码改为如下写法更合适:</span><br><span class="line">&lt;#assign x=&quot;Hello $&#123;user&#125;!&quot;&gt;</span><br></pre></td></tr></table></figure>
<h4 id="setting指令"><a href="#setting指令" class="headerlink" title="setting指令"></a>setting指令</h4><p>该指令用于设置FreeMarker的运行环境,该指令的语法格式如下:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&lt;#setting name=value&gt;</span><br></pre></td></tr></table></figure>
<p>在这个格式中,name的取值范围包含如下几个：</p>
<p>locale:该选项指定该模板所用的国家/语言选项 </p>
<p>number_format:指定格式化输出数字的格式</p>
<p>boolean_format:指定两个布尔值的语法格式,默认值是true,false </p>
<p>date_format,time_format,datetime_format:指定格式化输出日期的格式 </p>
<p>time_zone:设置格式化输出日期时所使用的时区</p>
<h4 id="自定义指令-macro指令-宏"><a href="#自定义指令-macro指令-宏" class="headerlink" title="自定义指令(macro指令)(宏)"></a>自定义指令(macro指令)(宏)</h4><p>语法：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">&lt;#macro name param1 param2 ... paramN&gt;</span><br><span class="line">...</span><br><span class="line">&lt;#nested loopvar1, loopvar2, ..., loopvarN&gt;</span><br><span class="line">...</span><br><span class="line">&lt;#return&gt;</span><br><span class="line">...</span><br><span class="line">&lt;/#macro&gt;</span><br></pre></td></tr></table></figure>
<p>用例：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">//定义名为test的指令</span><br><span class="line">&lt;#macro test foo bar=&quot;Bar&quot; baaz=-1&gt;</span><br><span class="line">这是自定义指令: $&#123;foo&#125;, $&#123;bar&#125;, $&#123;baaz&#125;</span><br><span class="line">&lt;/#macro&gt;</span><br><span class="line"></span><br><span class="line">//调用test指令</span><br><span class="line">&lt;@test foo=&quot;a&quot; bar=&quot;b&quot; baaz=5*5-2/&gt; //这是自定义指令: a, b, 23</span><br><span class="line">&lt;@test foo=&quot;a&quot; bar=&quot;b&quot;/&gt;            //这是自定义指令: a, b, -1</span><br><span class="line">&lt;@test foo=&quot;a&quot; baaz=5*5-2/&gt;         //这是自定义指令: a, Bar, 23</span><br><span class="line">&lt;@test foo=&quot;a&quot;/&gt;                    //这是自定义指令: a, Bar, -1</span><br></pre></td></tr></table></figure>
<div class="note default no-icon"><p>可以提前返回，比如&lt;#return/&gt; 但是不能&lt;#return 1&gt;， ==A macro cannot return a value==<br>==宏主要作用是拼接内容，把宏内部的字符串展示出来，return返回值没有意义==。</p></div>

<h4 id="function指令-函数"><a href="#function指令-函数" class="headerlink" title="function指令(函数)"></a>function指令(函数)</h4><p>用例：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"> &lt;#function buildPageUrl url pageNum data&gt;</span><br><span class="line"></span><br><span class="line">    &lt;#assign pageUrl = &quot;$&#123;url&#125;?pageNum=$&#123;pageNum&#125;&amp;pageSize=$&#123;data.pageSize&#125;&quot;&gt;</span><br><span class="line"></span><br><span class="line">    &lt;#return pageUrl/&gt;</span><br><span class="line"></span><br><span class="line">&lt;/#function&gt;</span><br><span class="line"></span><br><span class="line">$&#123;buildPageUrl(url2,page.pageNum+1,page)&#125;</span><br></pre></td></tr></table></figure>
<div class="note default no-icon"><p>与宏的调用方式不同，直接 ${buildPageUrl(url2,page.pageNum+1,page)}执行函数。==返回值才是最关键的结果，不是为了显示函数内部的字符串内容==。</p></div>


<h3 id="参考文章（特别鸣谢）："><a href="#参考文章（特别鸣谢）：" class="headerlink" title="参考文章（特别鸣谢）："></a>参考文章（特别鸣谢）：</h3><p><a href="https://blog.csdn.net/qq_34129814/article/details/76218863" target="_blank" rel="noopener">https://blog.csdn.net/qq_34129814/article/details/76218863</a></p>
<p><a href="https://segmentfault.com/a/1190000011768799" target="_blank" rel="noopener">https://segmentfault.com/a/1190000011768799</a></p>
<p><a href="https://blog.csdn.net/fhx007/article/details/7902040/" target="_blank" rel="noopener">https://blog.csdn.net/fhx007/article/details/7902040/</a></p>
<p><a href="https://www.cnblogs.com/qitian1/p/6463098.html" target="_blank" rel="noopener">https://www.cnblogs.com/qitian1/p/6463098.html</a></p>
<hr>
<h4 id="源码地址："><a href="#源码地址：" class="headerlink" title="源码地址："></a>源码地址：</h4><h6 id="github-https-github-com-542869246-myfreemarker"><a href="#github-https-github-com-542869246-myfreemarker" class="headerlink" title="github: https://github.com/542869246/myfreemarker"></a>github: <a href="https://github.com/542869246/myfreemarker" target="_blank" rel="noopener">https://github.com/542869246/myfreemarker</a></h6><h6 id="码云-https-gitee-com-zyf542869246-myfreemarker"><a href="#码云-https-gitee-com-zyf542869246-myfreemarker" class="headerlink" title="码云: https://gitee.com/zyf542869246/myfreemarker"></a>码云: <a href="https://gitee.com/zyf542869246/myfreemarker" target="_blank" rel="noopener">https://gitee.com/zyf542869246/myfreemarker</a></h6><hr>
<h6 id="Author-周宇峰"><a href="#Author-周宇峰" class="headerlink" title="Author:周宇峰"></a>Author:周宇峰</h6><h6 id="Github-https-github-com-542869246"><a href="#Github-https-github-com-542869246" class="headerlink" title="Github:https://github.com/542869246"></a>Github:<a href="https://github.com/542869246" target="_blank" rel="noopener">https://github.com/542869246</a></h6><h6 id="码云-https-gitee-com-zyf542869246"><a href="#码云-https-gitee-com-zyf542869246" class="headerlink" title="码云:https://gitee.com/zyf542869246"></a>码云:<a href="https://gitee.com/zyf542869246" target="_blank" rel="noopener">https://gitee.com/zyf542869246</a></h6><h6 id="Time-2018-5-14-1-45-11"><a href="#Time-2018-5-14-1-45-11" class="headerlink" title="Time:2018/5/14 1:45:11"></a>Time:2018/5/14 1:45:11</h6>
      
    </div>

    

    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>如果你觉得这篇文章对你有用，欢迎赞赏哦~</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="https://yfzhou.oss-cn-beijing.aliyuncs.com/blog/img/wechatpay.png" alt="Felix 微信支付"/>
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="https://yfzhou.oss-cn-beijing.aliyuncs.com/blog/img/alipay.png" alt="Felix 支付宝"/>
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    
	
	<div>
  
    <div>
    
        <div style="text-align: center;font-size: 13px;letter-spacing: 10px;user-select: none;margin-top: 50px;color: #bbb;">本文结束啦 <i class="fa fa-star"></i> 感谢您阅读</div>
    
</div>
  
</div>

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/java/" rel="tag"><i class="fa fa-tag"></i> java</a>
          
            <a href="/tags/FreeMarker/" rel="tag"><i class="fa fa-tag"></i> FreeMarker</a>
          
            <a href="/tags/模板引擎/" rel="tag"><i class="fa fa-tag"></i> 模板引擎</a>
          
        </div>
      

      
      
        <div class="post-widgets">
        

        

        
          
          <div class="social_share">
            
            
               <div id="needsharebutton-postbottom">
                 <span class="btn" title="分享">
                    <i class="fa fa-share-alt" aria-hidden="true"></i>
                 </span>
               </div>
            
          </div>
        
        </div>
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
			
			   <a href="/2018/08/07/Hexo-Next搭建个人博客（安装与部署）/" rel="prev" title="Hexo-Next搭建个人博客（安装与部署）">
			   <i class="fa fa-chevron-left"></i> Hexo-Next搭建个人博客（安装与部署）
			   
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
             
				<a href="/2018/07/30/My-New-Project/" rel="next" title="My New Project">
				My New Project <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>


  </div>


          </div>
          

  
    <div class="comments" id="comments">
      <div id="lv-container" data-id="city" data-uid="MTAyMC8zODUyNC8xNTA1Mg=="></div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
      <div id="sidebar-dimmer"></div>
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
			<a href="/">
              <img class="site-author-image" itemprop="image"
                src="https://yfzhou.oss-cn-beijing.aliyuncs.com/blog/img/user_head_img.jpg"
                alt="Felix" />
				</a>
            
              <p class="site-author-name" itemprop="name">Felix</p>
              <p class="site-description motion-element" itemprop="description">周宇峰的博客</p>
          </div>

          
            <nav class="site-state motion-element">
              
                <div class="site-state-item site-state-posts">
                
                  <a href="/archives/">
                
                    <span class="site-state-item-count">94</span>
                    <span class="site-state-item-name">日志</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-categories">
                  <a href="/categories/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">16</span>
                    <span class="site-state-item-name">分类</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-tags">
                  <a href="/tags/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">88</span>
                    <span class="site-state-item-name">标签</span>
                  </a>
                </div>
              
            </nav>
          

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
              
                <span class="links-of-author-item">
                  <a href="https://github.com/542869246" target="_blank" title="GitHub"><i class="fa fa-fw fa-github"></i>GitHub</a>
                  
                </span>
              
                <span class="links-of-author-item">
                  <a href="https://gitee.com/zyf542869246" target="_blank" title="Gitee"><i class="fa fa-fw fa-git"></i>Gitee</a>
                  
                </span>
              
                <span class="links-of-author-item">
                  <a href="https://music.163.com/#/user/home?id=343583524" target="_blank" title="网易云音乐"><i class="fa fa-fw fa-music"></i>网易云音乐</a>
                  
                </span>
              
                <span class="links-of-author-item">
                  <a href="https://www.zhihu.com/people/yu-sui-58/activities" target="_blank" title="知乎"><i class="fa fa-fw fa-globe"></i>知乎</a>
                  
                </span>
              
            </div>
          

          
          

          
          
            <div class="links-of-blogroll motion-element links-of-blogroll-block">
              <div class="links-of-blogroll-title">
                <i class="fa  fa-fw fa-link"></i>
                友情链接
              </div>
              <ul class="links-of-blogroll-list">
                
                  <li class="links-of-blogroll-item">
                    <a href="http://zblog.dawnings.top/" title="删库东😎" target="_blank">删库东😎</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://ntssl.cn" title="ntssl.cn" target="_blank">ntssl.cn</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://blog.imyzt.top/" title="imyzt" target="_blank">imyzt</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://www.charmsongo.cn/" title="charmsongo" target="_blank">charmsongo</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://www.52share.online" title="HuiProgramer" target="_blank">HuiProgramer</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://music.163.com/#/user/home?id=343583524" title="😆 网易云音乐 😆" target="_blank">😆 网易云音乐 😆</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://www.zhihu.com/people/yu-sui-58/activities" title="😤 知乎 😤" target="_blank">😤 知乎 😤</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://www.ityouknow.com/spring-boot.html" title="spring-boot 纯洁的微笑" target="_blank">spring-boot 纯洁的微笑</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000" title="Python教程 廖雪峰" target="_blank">Python教程 廖雪峰</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="/about" title="关于此博客" target="_blank">关于此博客</a>
                  </li>
                
              </ul>
			  <div id="days"></div>
<script>
function show_date_time(){
window.setTimeout("show_date_time()", 1000);
BirthDay=new Date("07/30/2018 15:13:14");
today=new Date();
timeold=(today.getTime()-BirthDay.getTime());
sectimeold=timeold/1000
secondsold=Math.floor(sectimeold);
msPerDay=24*60*60*1000
e_daysold=timeold/msPerDay
daysold=Math.floor(e_daysold);
e_hrsold=(e_daysold-daysold)*24;
hrsold=setzero(Math.floor(e_hrsold));
e_minsold=(e_hrsold-hrsold)*60;
minsold=setzero(Math.floor((e_hrsold-hrsold)*60));
seconds=setzero(Math.floor((e_minsold-minsold)*60));
document.getElementById('days').innerHTML="已运行"+daysold+"天"+hrsold+"小时"+minsold+"分"+seconds+"秒";
}
function setzero(i){
if (i<10)
{i="0" + i};
return i;
}
show_date_time();
</script>
            </div>
          

          
            
          
          <div id="days"></div>
<script>
function show_date_time(){
window.setTimeout("show_date_time()", 1000);
BirthDay=new Date("07/30/2018 15:13:14");
today=new Date();
timeold=(today.getTime()-BirthDay.getTime());
sectimeold=timeold/1000
secondsold=Math.floor(sectimeold);
msPerDay=24*60*60*1000
e_daysold=timeold/msPerDay
daysold=Math.floor(e_daysold);
e_hrsold=(e_daysold-daysold)*24;
hrsold=setzero(Math.floor(e_hrsold));
e_minsold=(e_hrsold-hrsold)*60;
minsold=setzero(Math.floor((e_hrsold-hrsold)*60));
seconds=setzero(Math.floor((e_minsold-minsold)*60));
document.getElementById('days').innerHTML="已运行"+daysold+"天"+hrsold+"小时"+minsold+"分"+seconds+"秒";
}
function setzero(i){
if (i<10)
{i="0" + i};
return i;
}
show_date_time();
</script>
        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-5"><a class="nav-link" href="#FreeMarker是一个很值得去学习的模版引擎。它是基于模板文件生成其他文本的通用工具。本章内容通过如何使用FreeMarker生成Html-web-页面-和-代码自动生成工具来快速了解FreeMarker。"><span class="nav-number">1.</span> <span class="nav-text">FreeMarker是一个很值得去学习的模版引擎。它是基于模板文件生成其他文本的通用工具。本章内容通过如何使用FreeMarker生成Html web 页面 和 代码自动生成工具来快速了解FreeMarker。</span></a></li></ol></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#简介"><span class="nav-number"></span> <span class="nav-text">简介</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#特点"><span class="nav-number">1.</span> <span class="nav-text">特点</span></a></li></ol></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#FreeMarker-程序"><span class="nav-number"></span> <span class="nav-text">FreeMarker 程序</span></a><ol class="nav-child"><li class="nav-item nav-level-6"><a class="nav-link" href="#项目目录结构"><span class="nav-number">0.1.</span> <span class="nav-text">项目目录结构</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#eclipse安装freemarker插件"><span class="nav-number">0.2.</span> <span class="nav-text">eclipse安装freemarker插件</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#maven依赖"><span class="nav-number">0.3.</span> <span class="nav-text">maven依赖</span></a></li></ol></li></ol></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#语法详解"><span class="nav-number"></span> <span class="nav-text">语法详解</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#数据类型"><span class="nav-number"></span> <span class="nav-text">数据类型</span></a><ol class="nav-child"><li class="nav-item nav-level-6"><a class="nav-link" href="#和java不同，FreeMarker不需要定义变量的类型，直接赋值即可。"><span class="nav-number">0.1.</span> <span class="nav-text">和java不同，FreeMarker不需要定义变量的类型，直接赋值即可。</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#注释：-lt-–-abcd-–-gt"><span class="nav-number">0.2.</span> <span class="nav-text">注释：&lt;#– abcd –&gt;</span></a></li></ol></li></ol></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#字符串操作"><span class="nav-number"></span> <span class="nav-text">字符串操作</span></a><ol class="nav-child"><li class="nav-item nav-level-6"><a class="nav-link" href="#声明变量和输出"><span class="nav-number">0.1.</span> <span class="nav-text">声明变量和输出:</span></a></li></ol></li><li class="nav-item nav-level-5"><a class="nav-link" href="#字符串连接："><span class="nav-number">1.</span> <span class="nav-text">字符串连接：</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#字符串截取："><span class="nav-number">2.</span> <span class="nav-text">字符串截取：</span></a></li></ol></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#算数运算："><span class="nav-number"></span> <span class="nav-text">算数运算：</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#比较运算符"><span class="nav-number"></span> <span class="nav-text">比较运算符</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#逻辑运算符"><span class="nav-number"></span> <span class="nav-text">逻辑运算符</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#内建函数"><span class="nav-number"></span> <span class="nav-text">内建函数</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#字符串相关常用的内建函数："><span class="nav-number">1.</span> <span class="nav-text">字符串相关常用的内建函数：</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#集合相关常用的内建函数："><span class="nav-number">2.</span> <span class="nav-text">集合相关常用的内建函数：</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#数字值相关常用的内建函数："><span class="nav-number">3.</span> <span class="nav-text">数字值相关常用的内建函数：</span></a></li></ol></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#三元运算符"><span class="nav-number"></span> <span class="nav-text">三元运算符</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#空值处理运算符"><span class="nav-number"></span> <span class="nav-text">空值处理运算符</span></a><ol class="nav-child"><li class="nav-item nav-level-6"><a class="nav-link" href="#FreeMarker提供两个运算符来避免空值"><span class="nav-number">0.1.</span> <span class="nav-text">FreeMarker提供两个运算符来避免空值</span></a></li></ol></li></ol></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#常用指令"><span class="nav-number"></span> <span class="nav-text">常用指令</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#if指令"><span class="nav-number"></span> <span class="nav-text">if指令</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#switch-case指令"><span class="nav-number"></span> <span class="nav-text">switch case指令</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#list指令"><span class="nav-number"></span> <span class="nav-text">list指令</span></a><ol class="nav-child"><li class="nav-item nav-level-6"><a class="nav-link" href="#List指令还隐含了两个循环变量："><span class="nav-number">0.1.</span> <span class="nav-text">List指令还隐含了两个循环变量：</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#对List进行排序"><span class="nav-number">0.2.</span> <span class="nav-text">对List进行排序</span></a></li></ol></li><li class="nav-item nav-level-5"><a class="nav-link" href="#使用list指令遍历map"><span class="nav-number">1.</span> <span class="nav-text">使用list指令遍历map</span></a></li></ol></li><li class="nav-item nav-level-4"><a class="nav-link" href="#include指令"><span class="nav-number"></span> <span class="nav-text">include指令</span></a><ol class="nav-child"><li class="nav-item nav-level-6"><a class="nav-link" href="#总结：出现这种情况，在-两个模版中都分别存在变量名都相同的变量的时候，include包含进来，会进行覆盖-，include只时候将其公共的静态文件进行包含，而里面不涉及到内部函数以及变量声明之类的，当涉及到这种问题，我们就要用import进行导入"><span class="nav-number">0.1.</span> <span class="nav-text">总结：出现这种情况，在==两个模版中都分别存在变量名都相同的变量的时候，include包含进来，会进行覆盖==，include只时候将其公共的静态文件进行包含，而里面不涉及到内部函数以及变量声明之类的，当涉及到这种问题，我们就要用import进行导入</span></a></li></ol></li></ol></li><li class="nav-item nav-level-4"><a class="nav-link" href="#import指令"><span class="nav-number"></span> <span class="nav-text">import指令</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#noparse指令"><span class="nav-number"></span> <span class="nav-text">noparse指令</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#assign指令"><span class="nav-number"></span> <span class="nav-text">assign指令</span></a><ol class="nav-child"><li class="nav-item nav-level-6"><a class="nav-link" href="#虽然assign指定了这种复杂变量值的用法-但是我们也不要滥用这种用法-如下例子"><span class="nav-number">0.1.</span> <span class="nav-text">虽然assign指定了这种复杂变量值的用法,但是我们也不要滥用这种用法,如下例子:</span></a></li></ol></li></ol></li><li class="nav-item nav-level-4"><a class="nav-link" href="#setting指令"><span class="nav-number"></span> <span class="nav-text">setting指令</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#自定义指令-macro指令-宏"><span class="nav-number"></span> <span class="nav-text">自定义指令(macro指令)(宏)</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#function指令-函数"><span class="nav-number"></span> <span class="nav-text">function指令(函数)</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#参考文章（特别鸣谢）："><span class="nav-number"></span> <span class="nav-text">参考文章（特别鸣谢）：</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#源码地址："><span class="nav-number"></span> <span class="nav-text">源码地址：</span></a><ol class="nav-child"><li class="nav-item nav-level-6"><a class="nav-link" href="#github-https-github-com-542869246-myfreemarker"><span class="nav-number">0.1.</span> <span class="nav-text">github: https://github.com/542869246/myfreemarker</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#码云-https-gitee-com-zyf542869246-myfreemarker"><span class="nav-number">0.2.</span> <span class="nav-text">码云: https://gitee.com/zyf542869246/myfreemarker</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#Author-周宇峰"><span class="nav-number">0.3.</span> <span class="nav-text">Author:周宇峰</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#Github-https-github-com-542869246"><span class="nav-number">0.4.</span> <span class="nav-text">Github:https://github.com/542869246</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#码云-https-gitee-com-zyf542869246"><span class="nav-number">0.5.</span> <span class="nav-text">码云:https://gitee.com/zyf542869246</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#Time-2018-5-14-1-45-11"><span class="nav-number">0.6.</span> <span class="nav-text">Time:2018/5/14 1:45:11</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2018 – <span itemprop="copyrightYear">2019</span>
  <span class="with-love" id="animate">
    <i class="fa fa-tint"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Felix</span>

  
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    
      <span class="post-meta-item-text">站点总字数：</span>
    
    <span title="站点总字数">538k</span>
  

  
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
    
      <span class="post-meta-item-text">站点阅读时长 &asymp;</span>
    
    <span title="站点阅读时长">11:13</span>
  
  
  <div style="background-image:linear-gradient(90deg,#6dba82 0,#07b39b 15%,#1098ad 30%,#5073b8 44%,#a166ab 58%,#ef4e7b 72%,#f37055 86%,#f79533 100%);background-size:cover;-webkit-background-clip:text;-webkit-text-fill-color:transparent;user-select:none"><i>Tip: 本站电脑访问体验更佳耶&nbsp;<i class="fa fa-angellist" style="display:inline"></i></i></div>
  
</div>


<!--

  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动 v3.7.1</div>





-->



  <span>Hosted by <a href="https://pages.coding.me" >Coding Pages</a></span>



<div class="weixin-box">
  <div class="weixin-menu">
    <div class="weixin-hover">
      <div class="weixin-description">微信扫一扫，加好友</div>
    </div>
  </div>
</div>

        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv" title="总访客量">
      <i class="fa fa-user"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
    </span>
  

  
    <span class="site-pv" title="总访问量">
      <i class="fa fa-eye"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
    </span>
  
</div>









        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
          <span id="scrollpercent"><span>0</span>%</span>
        
      </div>
    

    
      <div id="needsharebutton-float">
        <span class="btn">
          <i class="fa fa-share-alt" aria-hidden="true"></i>
        </span>
      </div>
    
	
    

    
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>












  















  
  
    <script type="text/javascript" src="//cdn.jsdelivr.net/jquery/2.1.3/jquery.min.js"></script>
  

  
  
    <script type="text/javascript" src="//cdn.jsdelivr.net/velocity/1.2.3/velocity.min.js"></script>
  

  
  
    <script type="text/javascript" src="//cdn.jsdelivr.net/velocity/1.2.3/velocity.ui.min.js"></script>
  

  
  
    <script type="text/javascript" src="//cdn.jsdelivr.net/fancybox/2.1.5/jquery.fancybox.pack.js"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=6.4.1"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=6.4.1"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=6.4.1"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=6.4.1"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=6.4.1"></script>



  



  
    <script type="text/javascript">
      window.livereOptions = {
        refer: '2018/08/01/FreeMarker笔记/'
      };
      (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
      })(document, 'script');
    </script>
  









  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  
  <script>
    
    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();

      Counter('get', '/classes/Counter', { where: JSON.stringify({ url }) })
        .done(function ({ results }) {
          if (results.length > 0) {
            var counter = results[0];
            
              var $element = $(document.getElementById(url));
              $element.find('.leancloud-visitors-count').text(counter.time + 1);
            
            Counter('put', `/classes/Counter/${counter.objectId}`, JSON.stringify({ time: { "__op":"Increment", "amount":1 } }))
            
            .fail(function ({ responseJSON }) {
                console.log('Failed to save Visitor num, with error message: ' + responseJSON.error);
            })
          } else {
            
              var $element = $(document.getElementById(url));
              $element.find('.leancloud-visitors-count').text('Counter not initialized! See more at console err msg.');
              console.error('ATTENTION! LeanCloud counter has security bug, see here how to solve it: https://github.com/theme-next/hexo-leancloud-counter-security. \n But you also can use LeanCloud without security, by set \'security\' option to \'false\'.');
            
          }
        })
      .fail(function ({ responseJSON }) {
        console.log('LeanCloud Counter Error:' + responseJSON.code + " " + responseJSON.error);
      });
    }
    

    $(function() {
      $.get('https://app-router.leancloud.cn/2/route?appId=' + "4DkhRkq5CadWFisToA3zFrop-gzGzoHsz")
        .done(function ({ api_server }) {
          var Counter = function (method, url, data) {
            return $.ajax({
              method: method,
              url: `https://${api_server}/1.1${url}`,
              headers: {
                'X-LC-Id': "4DkhRkq5CadWFisToA3zFrop-gzGzoHsz",
                'X-LC-Key': "xihAA2ETGTdekJFloguCmmgq",
                'Content-Type': 'application/json',
              },
              data: data,
            });
          };
          
          addCount(Counter);
          
        })
    });
  </script>



  

  

  

  
  
  
  <script src="/lib/needsharebutton/needsharebutton.js"></script>

  <script>
    
      pbOptions = {};
      
          pbOptions.iconStyle = "default";
      
          pbOptions.boxForm = "horizontal";
      
          pbOptions.position = "bottomCenter";
      
          pbOptions.networks = "Weibo,Wechat,Douban,QQZone,Twitter,Linkedin,Mailto,Reddit,Delicious,StumbleUpon,Pinterest,Facebook,GooglePlus,Slashdot,Technorati,Posterous,Tumblr,GoogleBookmarks,Newsvine,Evernote,Friendfeed,Vkontakte,Odnoklassniki,Mailru";
      
      new needShareButton('#needsharebutton-postbottom', pbOptions);
    
    
      flOptions = {};
      
          flOptions.iconStyle = "default";
      
          flOptions.boxForm = "horizontal";
      
          flOptions.position = "middleRight";
      
          flOptions.networks = "Weibo,Wechat,Douban,QQZone,Twitter,Linkedin,Mailto,Facebook,Tumblr,Friendfeed";
      
      new needShareButton('#needsharebutton-float', flOptions);
    
  </script>

  

  

  

  

  

  

  
  <div class="bg_content">
	<canvas id="canvas"></canvas>
	<canvas id="canvas1"></canvas>
	  <!-- html5-canvas-animation
	  <div class="canvas-wrap">
		<div id="canvas3" class="gradient"></div>
	</div>-->
  </div>
  
  
  
  <!-- 右上角github关注-->
  <div class="forkme">
	<!--<a href="https://github.com/542869246">
	<img style="position: absolute; top: 0; right: 0; border: 0;" src="http://pd2tflnys.bkt.clouddn.com/img/blog/forkme_right_red_aa0000.png" alt="Fork me on GitHub">
	</a>-->
	<a href="https://github.com/542869246" class="github-corner" aria-label="View source on GitHub">
	<svg width="80" height="80" viewBox="0 0 250 250" style="fill:#70B7FD; color:#fff; position: absolute; top: 0; border: 0; right: 0;" aria-hidden="true">
	<path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path>
	<path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path>
	</svg>
	</a>
	<style>.github-corner:hover .octo-arm{animation:octocat-wave 560ms ease-in-out}@keyframes octocat-wave{0%,100%{transform:rotate(0)}20%,60%{transform:rotate(-25deg)}40%,80%{transform:rotate(10deg)}}@media (max-width:500px){.github-corner:hover .octo-arm{animation:none}.github-corner .octo-arm{animation:octocat-wave 560ms ease-in-out}}</style>
  </div>
  
  <!-- 音乐播放器-->
  <link rel="stylesheet" href="/dist/APlayer.min.css">
  <div id="aplayer"></div>
  <script type="text/javascript" src="/dist/APlayer.min.js"></script>
  <script type="text/javascript" src="/dist/music.js"></script>
 
   <!-- 页面点击小红心 -->
<script type="text/javascript" src="/js/src/clicklove.js"></script>
 <!-- 页面点击汉字 -->
<script type="text/javascript" src="/js/src/hanzi.js"></script>
  
  <!-- 代码块复制功能 -->
<script type="text/javascript" src="/js/src/clipboard.min.js"></script>  
<script type="text/javascript" src="/js/src/clipboard-use.js"></script>
<!-- 流星雨-->
<!--<script type="text/javascript" src="/js/src/meteor-rain.js"></script>-->
<!-- 粒子效果-->
<script type="text/javascript" src="/js/src/dynamic_bg.js"></script>

<!-- html5-canvas-animation-->
<!-- Main library
<script src="/js/src/three.min.js"></script> -->
<!-- Helpers
<script src="/js/src/projector.js"></script>
<script src="/js/src/canvas-renderer.js"></script> -->
<!-- Visualitzation adjustments 
<script src="/js/src/3d-lines-animation.js"></script>-->
<!-- Animated background color 
<script src="/js/src/color.js"></script>-->



</body>
</html>
